package com.example.dell.basic;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.example.dell.basicapplication.R;
import com.example.dell.boradcast.BoardCastUtils;
import com.example.dell.boradcast.PrensentView;
import com.example.dell.interfacepack.BackCall;
import com.example.dell.utils.DialogUtil;
import com.example.dell.weigit.LoadingView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

//所有界面所共有的基类
public abstract class BasicAllActivity extends AppCompatActivity implements PrensentView {


    private static final int               MY_PERMISIONLIST = 100;
    private static final int               MY_SINGLE        = 101;
    //app的基本权限
    private              String[]          permissionss     = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
    };
    private              ArrayList<Object> mPermissionList;

    private              BoardCastUtils    mCastUtils;
    private LoadingView mDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //1.权限的申请
        //（0.1）权限组
        getListPermissions(permissionss);
        //（0.2）单个权限
        //boolean singlePermission = getSinglePermission(Manifest.permission.CAMERA);

        //2，加载进度圈
        //showLoading()/hideProgree()

        //3，跳转是否付finsh掉
        //skipOtherActivity();

        //4,开启广播
        if (needNetListion()) {
            //设置网络监听
            //注册监听网络等这里还需要再加一个String flg来确定请求框架，暂时只是留个接口
            if (needNetListion()) {
                mCastUtils = new BoardCastUtils();
                mCastUtils.netWork(BasicAllActivity.this);
                mCastUtils.sreamWork(BasicAllActivity.this);
            }
        }


    }

    /**
     * 判断是否有网络
     */
    protected boolean isConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }

    /**
     * @param clazz   要跳转到的类
     * @param isFinsh 是否销毁当前界面
     */
    protected void skipOtherActivity(Class clazz, boolean isFinsh) {
        startActivity(new Intent(BasicAllActivity.this, clazz));
        if (isFinsh) {
            BasicAllActivity.this.finish();
        }
    }



    @Override
    protected void onStart() {
        super.onStart();
        //5,信息之间的传递
        if (isBindEventBus()) {
            EventBus.getDefault().register(BasicAllActivity.this);
        }
    }

    /**
     *
     * @return 是否开启信息的传递
     */
    public boolean isBindEventBus() {

        return false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (isBindEventBus()) {
            if (EventBus.getDefault().isRegistered(BasicAllActivity.this)) {
                EventBus.getDefault().unregister(BasicAllActivity.this);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDialog != null) {
            mDialog.dismiss();
            mDialog = null;
        }
        if (needNetListion()) {
            mCastUtils.unRegistNetWork(BasicAllActivity.this);
            mCastUtils.unRegistScreamWork(BasicAllActivity.this);
        }


    }

    /**
     * @param permissionss 权限组的集合
     */
    protected void getListPermissions(String[] permissionss) {
        // 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
        if (mPermissionList == null) {
            mPermissionList = new ArrayList<>();
        } else {
            mPermissionList.clear();
        }

        //检查版本是否大于M也就是5.0的手机
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            for (int i = 0; i < permissionss.length; i++) {

                //检查是否获取了权限
                if (ContextCompat.checkSelfPermission(BasicAllActivity.this, permissionss[i]) != PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permissionss[i]);
                }
            }

            if (!mPermissionList.isEmpty()) {
                //将List转为数组
                String[] permissionarrs = mPermissionList.toArray(new String[mPermissionList.size()]);

                ActivityCompat.requestPermissions(BasicAllActivity.this, permissionarrs, MY_PERMISIONLIST);
            }
        }
    }

    /**
     * @param permision 需要的单个权限
     */
    protected boolean getSinglePermission(String permision) {
        //检查版本是否大于M
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, permision) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{permision},
                        MY_SINGLE);
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //单项回调
        if (requestCode == MY_SINGLE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //                    showToast("权限已申请");
            } else {
                //                    showToast("权限已拒绝");
                //判断是否勾选禁止后不再询问
                boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(BasicAllActivity.this, permissions[0]);
                if (!showRequestPermission) {

                    DialogUtil.showSelectButton(BasicAllActivity.this, "权限管理", "需要读取内存卡权限才能进行其他操作", "去设置", "取消", new BackCall() {
                        @Override
                        public void deal(int which, int postion) {
                            super.deal(which, postion);
                            switch (postion) {
                                case 0:
                                    Intent intent = new Intent(
                                            Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    intent.setData(Uri.parse("package:" + getPackageName()));
                                    startActivity(intent);
                                    break;
                                case 1:
                                    finish();
                                    break;
                            }
                        }
                    }).show();

                } else {

                    DialogUtil.showSelectButton(BasicAllActivity.this, "权限管理", "需要读取内存卡权限才能进行其他操作", "去设置", "取消", new BackCall() {
                        @Override
                        public void deal(int which, int postion) {
                            super.deal(which, postion);
                            switch (postion) {
                                case 0:
                                    Intent intent = new Intent(
                                            Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    intent.setData(Uri.parse("package:" + getPackageName()));
                                    startActivity(intent);
                                    break;
                                case 1:
                                    finish();
                                    break;
                            }
                        }
                    }).show();

                }

            }

        } else if (requestCode == MY_PERMISIONLIST) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    //判断是否勾选禁止后不再询问
                    boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(BasicAllActivity.this, permissions[i]);
                    if (!showRequestPermission) {
                        DialogUtil.showSelectButton(BasicAllActivity.this, "权限管理", "需要读取内存卡权限才能进行其他操作", "去设置", "取消", new BackCall() {
                            @Override
                            public void deal(int which, int postion) {
                                super.deal(which, postion);
                                switch (postion) {
                                    case 0:
                                        Intent intent = new Intent(
                                                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                        intent.setData(Uri.parse("package:" + getPackageName()));
                                        startActivity(intent);
                                        break;
                                    case 1:
                                        finish();
                                        break;
                                }
                            }
                        }).show();
                        //权限组，只跳转设置界面一次
                        return;
                    } else {


                        DialogUtil.showSelectButton(BasicAllActivity.this, "权限管理", "需要读取内存卡权限才能进行其他操作", "去设置", "取消", new BackCall() {
                            @Override
                            public void deal(int which, int postion) {
                                super.deal(which, postion);
                                switch (postion) {
                                    case 0:
                                        Intent intent = new Intent(
                                                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                        intent.setData(Uri.parse("package:" + getPackageName()));
                                        startActivity(intent);
                                        break;
                                    case 1:
                                        finish();
                                        break;
                                }
                            }
                        }).show();

                        return;
                    }
                }
            }
        }

    }

    /**
     * @return 是否开启网络监听
     */
    protected boolean needNetListion() {

        return false;
    }

    @Override
    public void onNetChange(int netMobile) {

    }

    @Override
    public void onScreamState(int flg) {

    }

    protected void showLoading() {
        if (mDialog == null) {
            mDialog = new LoadingView(this, R.style.CustomDialog);
        }
        if (mDialog.getOwnerActivity()==null) {
            hideProgree();
            return;
        }else {
            mDialog.show();
        }

    }

    //隐藏加载进度圈
    protected void hideProgree() {
        if (mDialog != null) {
            mDialog.dismiss();
        }

    }

    public   void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
}
